/**
 * axios 封装
 * 
 */

import { Service } from '@element-plus/icons-vue'
import axios from 'axios'
import router from '@/router/router'
import { ElMessage } from 'element-plus'
import storage from './storage'


// 创建axios
const service = axios.create({
    baseURL:import.meta.env.VITE_APP_BASE_API, // 指定访问地址前缀
    timeout:5000
})

// 请求拦截
service.interceptors.request.use((req)=>{
    const headers = req.headers
    const token = storage.getItem("token") || {}
    if(!headers.Authorization){
        headers.Authorization = 'Bearer ' + token 
    }
    return req 
})

// 响应拦截
service.interceptors.response.use((res)=>{
    const {code, data, message} = res.data 
    if (code==403){
        ElMessage.error(message)
        // todo 
        storage.clearAll()
        setTimeout(()=>{
            router.push('/login')
        },1500)
    }else if (code==200){
        return res.data
    }else {
        ElMessage.error(message)
    }
})


// 核心函数
const request =(options)=>{
    options.method = options.method || 'get'
    if (options.method.toLowerCase()=='get'){
        options.params = options.data
    }
    service.defaults.baseURL = import.meta.env.VITE_APP_BASE_API
    return service(options)
    
}

export default request